<?php
/**
 * File: Http.php
 * User: LiaoJiangYi
 * Time: 2016/6/17 20:58
 * QQ:   527532113
 * WeChat: jyliao_vip
 * Mail: jyliao@vip.qq.com
 */
namespace Ext;
final class Http
{
    public static function httpBuildQuery($url, array $options)
    {
        if (!empty($options)) {
            $url .= (stripos($url, '?') === null ? '&' : '?') . http_build_query($options);
        }
        return $url;
    }
    public static function post($url, array $postOptions, array $options = [])
    {
        return self::parseHttpRequest(function($url, $postOptions) {
            return self::http($url, [
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => $postOptions
            ]);
        }, self::httpBuildQuery($url, $options), $postOptions);
    }
    public static function get($url, array $options = [])
    {
        return self::parseHttpRequest(function($url) {
            return self::http($url);
        }, self::httpBuildQuery($url, $options));
    }
    private static function parseHttpRequest(callable $callable, $url, $postOptions = null)
    {
        return $callable($url,$postOptions);
    }
    private static function http($url, $options = [])
    {
        $options = [
                CURLOPT_URL => $url,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_CONNECTTIMEOUT => 30,
                CURLOPT_RETURNTRANSFER => true,
            ] + (stripos($url, "https://") !== false ? [
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                //CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1,// 微信官方屏蔽了ssl2和ssl3, 启用更高级的ssl
            ] : []) + $options;
        $curl = curl_init();
        curl_setopt_array($curl, $options);
        @curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
        $content = curl_exec($curl);
        $status = curl_getinfo($curl);
        curl_close($curl);
        if (isset($status['http_code']) && $status['http_code'] == 200) {
            return $content;
        }
        return false;
    }
}